package com.example.universitylibraryback.pipeline.filter;

import com.example.universitylibraryback.entity.Reader;
import com.example.universitylibraryback.pipeline.BorrowContext;
import com.example.universitylibraryback.pipeline.Filter;
import com.example.universitylibraryback.service.ReaderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.concurrent.BlockingQueue;

/**
 * 读者资格校验过滤器
 * 负责校验读者的借阅资格
 */
@Component
public class ReaderQualificationFilter implements Filter<BorrowContext>, Runnable {
    private BlockingQueue<BorrowContext> inputQueue;
    private BlockingQueue<BorrowContext> outputQueue;

    @Autowired
    private ReaderService readerService;

    @Override
    public void process(BlockingQueue<BorrowContext> inputQueue, BlockingQueue<BorrowContext> outputQueue) throws InterruptedException {
        this.inputQueue = inputQueue;
        this.outputQueue = outputQueue;
        new Thread(this).start();
    }

    @Override
    public void run() {
        try {
            while (!Thread.currentThread().isInterrupted()) {
                BorrowContext context = inputQueue.take();
                if (context.isValid()) {
                    String readerId = context.getReaderId();
                    Reader reader = readerService.findById(readerId);
                    
                    if (reader == null) {
                        context.setValid(false);
                        context.setErrorMsg("读者不存在");
                    } else if (!"正常".equals(reader.getStatus())) {
                        context.setValid(false);
                        context.setErrorMsg("读者状态异常，无法借阅");
                    } else {
                        // 读者资格校验通过
                        context.setErrorMsg("读者资格校验通过");
                    }
                }
                outputQueue.put(context);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("ReaderQualificationFilter中断");
        }
    }
}